<template>
  <div class="group-store">
    <div class="table-title">
			<el-button type="primary" data-auth="bloc_role_add" @click="handleAdd">添加角色</el-button>
    </div>
    <div class="table-content">
      <el-table
        border
        :data="tableData"
        style="width: 100%">
        <el-table-column
          label="角色Id"
          prop="Id">
        </el-table-column>
        <el-table-column
          label="角色名"
          prop="Name">
        </el-table-column>
        <el-table-column
          label="角色类别"
          prop="RoleTypeName">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
						<el-button
              size="mini"
							type="primary"
              data-auth="bloc_role_modify"
              @click="handleEdit(scope.row)">编辑</el-button>
						<el-button
              size="mini"
							type="primary"
              data-auth="bloc_role_setauth"
              @click="setRole(scope.row)">设置权限</el-button>
						<el-button
              size="mini"
              data-auth="bloc_role_delete"
              @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="table-page">
			<el-pagination
			  background
				@size-change="changePage"
      	@current-change="getList"
      	:current-page.sync="searchData.pageIndex"
      	:page-sizes="[100, 200, 300, 400]"
			  layout="total,prev, pager, next"
			  :total="pageTotal">
			</el-pagination>
    </div>

		<el-dialog
			:title="dialogTitle"
			:visible.sync="roomShow"
			width="560px"
			center>
			<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px">
				<el-form-item label="角色名：" prop="Name">
					<el-input v-model="ruleForm.Name"></el-input>
				</el-form-item>
        <el-form-item label="角色类别：" prop="RoleType">
          <el-select v-model="ruleForm.RoleType" placeholder="请选择">
            <el-option
             label="集团角色"
             :value="1">
           </el-option>
           <el-option
            label="门店角色"
            :value="2">
          </el-option>
          </el-select>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button type="primary" @click="btnSave('ruleForm')">保存</el-button>
				<el-button @click="roomShow = false">取 消</el-button>
			</span>
		</el-dialog>

		<el-dialog
			:title="dialogTitle"
			:visible.sync="roleShow"
			width="700px"
			center>
      <div class="setroom-div">
        <el-tabs v-model="activeName">
          <el-tab-pane label="集团权限" name="first" v-if="setRoleData.RoleType===1">
            <div class="check-groups"><el-checkbox v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox></div>
          </el-tab-pane>
          <el-tab-pane label="门店权限" name="second" v-if="setRoleData.RoleType===2">
            <div class="check-groups"><el-checkbox v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox></div>
          </el-tab-pane>
        </el-tabs>
        <el-tree
          class="mx500"
          :data="setRoleData.RoleList"
          show-checkbox
          :node-key="'Id'"
          default-expand-all
          :default-checked-keys="checkList"
          :props="defaultProps"
          @check="changeTree"
          ref="tree">
        </el-tree>
      </div>
			<span slot="footer" class="dialog-footer">
				<el-button type="primary" @click="saveRole('ruleForm')">保存</el-button>
				<el-button @click="roleShow = false">取 消</el-button>
			</span>
		</el-dialog>

  </div>
</template>
<script>
  export default {
    data () {
      return {
        defaultProps: {
          children: 'Children',
          label: 'Name'
        },
        activeName:'first',
        checkAll:false,
        pageTotal:0,
        searchData:{
          OrgId:JSON.parse(sessionStorage.getItem('nowmenu')).Id,
					Grade:-1,
          pageIndex:1,
          pageSize:10
        },
        setRoleData:{
          RoleId:'',
          RoleList:[]
        },
        checkList:[],
				dateTime:[],
        tableData:[],
				infoShow:false,
        roleShow:false,
				userInfoData:{},
				dialogTitle:'',
				roomShow:false,
				ruleForm: {
          Name: "",
          RoleType: "",
        },
        hotelAuths:[],
        blocAuths:[],
        rules: {
          Name: [
            { required: true, message: '请输入角色姓名', trigger: 'blur' },
          ],
          RoleType: [
            { required: true,type:'number', message: '请选择角色类别', trigger: 'change' }
          ],
        }
      }
    },
    created(){
      this.initList();
    },
    methods:{
      initList(){
        this.roomShow=false;
				this.infoShow=false;
				this.roleShow=false;
        this.getList();
      },
      changePage(size){
        this.searchData.pageIndex=1;
        this.searchData.pageSize=size;
        this.getList();
      },
      getList(){
        this.$ajax.GetRoleListByPage(this.searchData).then(res=>{
          if(res.Success){
            this.tableData=res.Data.PagedData;
            this.pageTotal=res.Data.TotalCount;
          }
        })
      },
      resetForm(formName) {
        if(!this.$refs[formName]){return};
        this.$refs[formName].resetFields();
      },
			handleExcel(){
				let data=_.cloneDeep(this.searchData);
				data=this.$urlEncode(data);
				window.open(this.$api.GetMemberListToExcel+'?'+data);
			},
			handleAdd() {
        this.dialogTitle='添加角色';
        this.resetForm('ruleForm');
        this.ruleForm={
          Name: "",
          RoleType: "",
        };
        this.roomShow=true;
      },
      handleEdit(row) {
        this.dialogTitle='编辑角色';
        this.resetForm('ruleForm');
				this.ruleForm=_.cloneDeep(row);
				this.roomShow=true;
      },
      handleDelete(row) {
        this.deleteShow('确认删除此角色?',row.Id,'deleterole')
      },
      deleteShow(title,id,api){
        this.$confirm(title, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          let data={
            id:id
          };
          this.$ajax[api](data).then(res=>{
            if(res.Success){
              this.$message({
                type: 'success',
                message: '已删除!'
              });
              this.initList();
            }
          })
        }).catch(() => {
        });
      },
			btnSave(formName){
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$ajax.saverole(this.ruleForm).then(res=>{
              if(res.Success){
                this.$message.success(this.dialogTitle+'成功!');
                this.$refs[formName].resetFields();
                this.initList();
              }
            })
          } else {
            return false;
          }
        });
      },
      setRole(row){
        this.dialogTitle='设置权限';
        this.checkList=[];
        this.setRoleData.RoleId=row.Id;
        this.setRoleData.RoleType=row.RoleType;
        this.activeName=row.RoleType===1?'first':'second';
        this.$ajax.GetAllAuthority({type:row.RoleType}).then(res=>{
          if(res.Success){
            this.setRoleData.RoleList=res.Data;
            this.$ajax.GetAuthorities({id:row.Id}).then(res=>{
              if(res.Success){
                this.checkList=res.Data.map(item=>{
                  return item.Id
                })
                this.roleShow=true;
                this.$nextTick(()=>{
                  this.$refs.tree.setCheckedKeys(this.checkList);
                  this.getcheckAllHotel();
                })
              }
            })
          }
        })
      },
      handleCheckAllChange(val) {
        this.checkList=[];
        if(val){
          this.checkList=this.setRoleData.RoleList.map(item=>{
            return item.Id
          })
        }
        this.$nextTick(()=>{
          this.$refs.tree.setCheckedKeys(this.checkList);
        })
      },
      changeTree(rows,checkedRows){
        this.checkList=checkedRows.checkedKeys;
        this.getcheckAllHotel();
      },
      getcheckAllHotel(){
        this.checkAll=this.setRoleData.RoleList.every(item=>{return this.checkList.indexOf(item.Id)>=0});
      },
      saveRole() {
        let data={
          RoleId:this.setRoleData.RoleId,
          AuthIdList:[...this.checkList]
        }
        if(!data.AuthIdList.length){
          this.$message.info('请选择权限！')
          return;
        }
        this.$ajax.PackageAuthorities(data).then(res=>{
          if(res.Success){
            this.$message.success(this.dialogTitle+'成功!');
            this.initList();
          }
        })
      }
    }
  }
</script>
